package com.blue.base.oauth.resource.user.controller;

import com.blue.base.common.bean.resp.JsonResult;
import com.blue.base.oauth.common.bean.RemoteGetUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Arrays;
import java.util.UUID;

/**
 * 必須要有Bearer token的header请求才可以访问此接口
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public JsonResult get() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String account = (String) authentication.getPrincipal();
        log.info("account:{}", account);
        RemoteGetUserInfo detailDto = new RemoteGetUserInfo();
        detailDto.setAccount(account);
        detailDto.setAvatar("image://" + UUID.randomUUID().toString());
        detailDto.setRoles(Arrays.asList("ROLE_SIMPLE", "ROLE_ADMIN"));
        return JsonResult.ok(detailDto);
    }

    @GetMapping("/user1")
    public JsonResult user1(Principal principal) {
        return JsonResult.ok(principal);
    }

    @GetMapping("/user2")
    public JsonResult user2(Authentication authentication) {
        return JsonResult.ok(authentication);
    }

    @GetMapping("/user3")
    public JsonResult user3(HttpServletRequest request) {
        return JsonResult.ok(request.getUserPrincipal());
    }
}
